<?php

require_once 'config.php';

// ===============================
function participantExists($pid) {
    global $DATABASE_NAME;

    //start session
    if (!isset($_SESSION)) {
        session_start();
    }

    $conn = new MongoClient(); // connect
    //get database
    $db = $conn->selectDB($DATABASE_NAME);

    //search for pid
    $cursor = $db->participants->find(array("pid" => $pid));

    //close connection
    $conn->close();

    //send back the result
    if ($cursor->count() > 0) {
        return true;
    }

    return false;
}

//participants
// ===============================
function saveParticipant() {

    if (isset($_SESSION['pid']) && isset($_SESSION['ip'])) {
        global $DATABASE_NAME;

        //start session
        if (!isset($_SESSION)) {
            session_start();
        }
        // connect
        $conn = new MongoClient();
        //get database
        $db = $conn->selectDB($DATABASE_NAME);

        //create object
        $participant = array(
            "pid" => $_SESSION['pid'],
            "ip" => $_SESSION['ip'],
            'ts' => date("Y-m-d H:i:s")
        );

        //set email (if given)
        if (isset($_SESSION['email'])) {
            $participant['email'] = $_SESSION['email'];
        }

        //create collection
        $db->createCollection("participants");

        //inset object
        $db->participants->insert($participant);
        //close connection
        $conn->close();
    }
}

//save counterfactual questionnaires 
// ===============================
function saveCFQ($collection, $postData) {
    // save the results
    global $DATABASE_NAME;

    //start session
    if (!isset($_SESSION)) {
        session_start();
    }

    $conn = new MongoClient(); // connect
    //get database
    $db = $conn->selectDB($DATABASE_NAME);

    //create collection
    $db->createCollection($collection);

    $data = array();
    $data['pid'] = $_SESSION['pid'];
    $data['questionns'] = $postData;

    $db->selectCollection($collection)->insert($data);

    //close connection
    $conn->close();
}
